import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { deleteFileFun, getFileListFun, renameFileFun } from '@/services/ant-design-pro/panApi';
import { formatBits, getIconByType, isImage, isVideo } from '@/utils';
import { Checkbox, Dropdown, Empty, Flex, Input, message, Modal } from 'antd';
import type { MenuProps } from 'antd';
import AliSvg from '@/components/AliSvg';
import PreviewImage from '@/components/Preview/PreviewImage';
import PreviewVideo from '@/components/Preview/PreviewVideo';
import {
  DeleteOutlined,
  DownloadOutlined,
  EllipsisOutlined,
  ExclamationCircleFilled,
  FormOutlined,
} from '@ant-design/icons';
import { useModel } from '@@/exports';

interface nowFileItemType {
  fileId: string;
  fileName: string;
  fileSize: string;
  fileMd5: string;
  filePath: string;
  fileType: string;
}

const FileRowItem = forwardRef((props, ref) => {
  let [fileList, setFileList] = useState([]);
  const { confirm } = Modal;
  const [nowFileItem, setNowFileItem] = useState({} as nowFileItemType);
  const previewRef = useRef();
  const previewVideoRef = useRef();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [reName, setReName] = useState('');
  const { selectList, setSelectList } = useModel('itemSelect');

  // 获取文件列表
  const getTable = async () => {
    let filePid = props.getCurrBread().filePid;
    let res = await getFileListFun({
      fileName: '',
      filePid: filePid,
    });
    res.data.forEach((item) => {
      item.fileSize = formatBits(item.fileSize);
      item.checked = false;
    });
    setFileList(res.data);
  };

  useEffect(() => {
    (async () => {
      await getTable();
    })();
  }, []);

  // 点击的是文件
  const clickFile = async (item) => {
    // 预判图片
    if (isImage(item.fileType)) {
      previewRef.current.showPreview(item.fileId);
      return;
    }

    // 预览视频
    if (isVideo(item.fileType)) {
      previewVideoRef.current.showPreview(item.fileId);
      return;
    }

    message.error('暂不支持预览该文件');
  };

  // 点击的文件夹
  const clickFolder = (item) => {
    // 更新面包屑
    props.pushBread(item);
  };

  // 点击某一行时触发
  const clickRow = (item: { fileType?: string }) => {
    if (item.fileType) {
      clickFile(item);
    } else {
      clickFolder(item);
    }
  };

  // 全选/不全选
  const checkAll = (check) => {
    setSelectList(check ? fileList : []);
  };

  // 导出方法
  useImperativeHandle(ref, () => {
    return {
      getTable,
      checkAll,
    };
  });

  // 点击操作小圆点触发
  const clickDropdown = (item) => {
    // 保存当前点击的文件信息
    setNowFileItem(item);
  };

  // 删除文件
  const removeFileItem = () => {
    confirm({
      title: '提示',
      icon: <ExclamationCircleFilled />,
      content: '确认删除吗?',
      onOk: async () => {
        await deleteFileFun(nowFileItem);
        message.success('删除成功');
        await getTable();
        props.updateFileNumber();
      },
    });
  };

  // 改变文件名称
  const changeReName = (val) => {
    setReName(val.currentTarget.value);
  };

  const openRenameModal = () => {
    setIsModalOpen(true);
    // 如果时文件，则只显示文件名称，不显示后缀
    if (nowFileItem.fileType) {
      setReName(nowFileItem.fileName.substring(0, nowFileItem.fileName.lastIndexOf('.')));
    } else {
      setReName(nowFileItem.fileName);
    }
  };

  // 关闭重命名弹框
  const closeDirModal = () => {
    setReName('');
    setIsModalOpen(false);
  };

  // 确认重命名
  const submitReName = () => {
    if (!reName) {
      message.error('文件名称不能为空');
      return;
    }
    renameFileFun({
      ...nowFileItem,
      fileName: reName + (nowFileItem.fileType || ''),
      fileSize: 0,
    }).then(async () => {
      message.success('重命名成功');
      closeDirModal();
      await getTable();
    });
  };

  // 下载文件
  const downloadFile = () => {
    if (!nowFileItem.fileType) {
      message.error('文件夹不能下载');
      return;
    }
    let a = document.createElement('a');
    a.href = `/api/pan/downloadFile/${nowFileItem.fileId}`;
    a.download = nowFileItem.fileName;
    a.click();
  };

  const changeItemCheck = (e, item) => {
    if (e.target.checked) {
      setSelectList((prev) => [...prev, item]);
    } else {
      setSelectList((prev) => prev.filter((p) => p.fileId !== item.fileId));
    }
  };

  useEffect(() => {
    if (selectList.length > 0 && selectList.length === fileList.length) {
      props.switchCheckAll(true);
    } else {
      props.switchCheckAll(false);
    }
  }, [selectList]);

  const getItemCheck = (fileId) => {
    return selectList.some((item) => item.fileId === fileId);
  };

  // 文件操作项
  const dropdownItems: MenuProps['items'] = [
    {
      label: (
        <div onClick={downloadFile}>
          <DownloadOutlined /> 下载
        </div>
      ),
      key: '0',
    },
    {
      label: (
        <div onClick={openRenameModal}>
          <FormOutlined /> 重命名
        </div>
      ),
      key: '1',
    },
    {
      label: (
        <div style={{ color: '#ff837b' }} onClick={removeFileItem}>
          <DeleteOutlined /> 删除
        </div>
      ),
      key: '2',
    },
  ];

  return (
    <div>
      {fileList.map((item, index) => {
        return (
          <div className={'item-content no-select file-item-tr'} key={index}>
            <div style={{ flex: 1, padding: '0 30px 0 0' }}>
              <Flex gap={10} align={'center'} justify={'space-between'}>
                {/*文件名称*/}
                <Flex gap={10} align={'center'} flex={1}>
                  {/*选择*/}
                  <Checkbox
                    checked={getItemCheck(item.fileId)}
                    onClick={(e) => changeItemCheck(e, item)}
                  />
                  {/*文件图标*/}
                  <AliSvg href={getIconByType(item)} />
                  {/*文件名称*/}
                  <div onClick={() => clickRow(item)} className={'text-ellipsis'}>
                    {item.fileName}
                  </div>
                </Flex>

                {/*文件操作下拉项*/}
                <Dropdown
                  menu={{ items: dropdownItems }}
                  trigger={['click']}
                  overlayStyle={{
                    width: '150px',
                  }}
                  onClick={() => clickDropdown(item)}
                >
                  <EllipsisOutlined className={'ellipsis-icon'} />
                </Dropdown>
              </Flex>
            </div>
            <div style={{ width: '200px' }}>{item.updateTime}</div>
            <div style={{ width: '150px' }}>{item.fileType ? item.fileSize : ''}</div>
          </div>
        );
      })}

      {fileList.length === 0 && (
        <div className={'empty-row'}>
          <Empty />
        </div>
      )}

      <PreviewImage ref={previewRef} />
      <PreviewVideo ref={previewVideoRef} />

      {/*新建文件夹弹框*/}
      <Modal
        title="重命名"
        width={400}
        open={isModalOpen}
        onCancel={closeDirModal}
        onOk={submitReName}
      >
        <div className={'modal-body'}>
          <AliSvg href={getIconByType(nowFileItem)} size={'8em'} />
          <Input placeholder="请输入新的名称" value={reName} onChange={changeReName} />
        </div>
      </Modal>
    </div>
  );
});

export default FileRowItem;
